;!function (win, doc) {
    var PKCms = function () {
            this.v = '2021';
            if (typeof $ === "undefined") {
                loadingJS('/statics/jquery/jquery-1.8.3.min.js');
            }
        },
        loadingJS = function (src) {
            var sobj = doc.createElement('script');
            sobj.type = "text/javascript";
            sobj.src = src + '?_' + Date.now();
            var headobj = doc.getElementsByTagName('head')[0];
            headobj.appendChild(sobj);
        },
        apiAjax = function (action, api_url, api_params, fn) {
            $.ajax({
                type: action,
                url: api_url,
                data: api_params,
                dataType: "JSON",
                cache: false,
                success: function (result) {
                    fn(null, result);
                },
                error: function (message) {
                    if (message.status === 500) {
                        fn('服务器返回异常')
                    } else {
                        fn(message);
                    }
                }
            });
        },
        apiResultHandler = function (apiResult, fn) {
            if (apiResult.hasOwnProperty('isSuccess')
                && apiResult.hasOwnProperty('msg')) {
                if (apiResult.isSuccess) {
                    if (apiResult.hasOwnProperty('data')) {
                        fn(null, null, apiResult.data, apiResult.count);
                    }
                } else {
                    fn(apiResult.msg, apiResult.code);
                }
            }
        },
        bin2hex = function (s) {
            var i, l, o = '', n;
            s += '';
            for (i = 0, l = s.length; i < l; i++) {
                n = s.charCodeAt(i)
                    .toString(16);
                o += n.length < 2 ? '0' + n : n;
            }
            return o;
        };

    PKCms.prototype.apiGet = function (api_url, api_params, fn) {
        apiAjax("GET", api_url, api_params, fn);
    };

    PKCms.prototype.apiPost = function (api_url, api_params, fn) {
        apiAjax("POST", api_url, api_params, fn);
    };

    PKCms.prototype.apiResultHandler = function (apiResult, fn) {
        if (apiResult != null && typeof apiResult == "string") {
            try {
                apiResult = JSON.parse(apiResult);
                if (typeof apiResult == "object") {
                    apiResultHandler(apiResult, fn);
                } else {
                    console.log('no json');
                    fn('返回的数据不是JSON格式', 500);
                }
            } catch (e) {
                console.log('no json');
                fn('返回的数据不是JSON格式', 500);
            }
        } else if (typeof apiResult == "object") {
            apiResultHandler(apiResult, fn);
        } else {
            console.log('no json');
            fn('返回的数据不是JSON格式', 500);
        }
    }

    // 交换数组元素
    PKCms.prototype.arraySort = {
        swapItems: function(arr, index1, index2) {
            arr[index1] = arr.splice(index2, 1, arr[index1])[0];
            return arr;
        },
        // 上移
        upRecord: function(arr, index) {
            if(index === 0) {
                return arr;
            }
            return this.swapItems(arr, index, index - 1);
        },
        // 下移
        downRecord: function(arr, index) {
            if(index === arr.length -1) {
                return arr;
            }
            return this.swapItems(arr, index, index + 1);
        }
    }

    PKCms.prototype.getArea = function (regional_code, fn) {
        apiGet('/index.php/RegionalLinkage/ApiGetAreaListByParent',
            {parentCode: regional_code},
            function (error, apiResult) {
                if (error) {
                    console.log('地区数据，出错：', error);
                } else {
                    win.PKCms.apiResultHandler(apiResult, function (error, code, result, count) {
                        if (error) {
                            console.log('地区数据，出错：', error);
                        } else {
                            fn(result, count);
                        }
                    });
                }
            });
    }

    PKCms.prototype.localStorage_set = function (params) {
        if (typeof params == "object") {
            for (var paramsKey in params) {
                if (paramsKey !== '') {
                    localStorage.setItem('PKCms_' + paramsKey, params[paramsKey]);
                }
            }
        }
    };

    PKCms.prototype.localStorage_get = function (key) {
        return localStorage.getItem('PKCms_' + key);
    };

    PKCms.prototype.localStorage_del = function (key) {
        localStorage.removeItem('PKCms_' + key);
    };

    PKCms.prototype.urlVarsToJSON = function (url) {
        var hash;
        var myJson = {};
        var hashes = url.slice(url.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            myJson[hash[0]] = hash[1];
        }
        return myJson;
    };

    PKCms.prototype.JSONToUrl = function (requestParams) {
        let params = [];
        Object.entries(requestParams).forEach(([key, value]) => {
            let param = key + '=' + encodeURI(value);
            params.push(param);
        });
        return params.join('&');
    }

    PKCms.prototype.uuid = function () {
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext("2d");
        var txt = location.hostname;
        ctx.textBaseline = "top";
        ctx.font = "14px 'Arial'";
        ctx.textBaseline = "tencent";
        ctx.fillStyle = "#f60";
        ctx.fillRect(125,1,62,20);
        ctx.fillStyle = "#069";
        ctx.fillText(txt, 2, 15);
        ctx.fillStyle = "rgba(102, 204, 0, 0.7)";
        ctx.fillText(txt, 4, 17);

        var b64 = canvas.toDataURL().replace("data:image/png;base64,","");
        var bin = atob(b64);
        return bin2hex(bin.slice(-16,-12));
    }
    
    PKCms.prototype.isURL = function (str_url, callback) {
        var strRegex = "^((https|http|ftp|rtsp|mms)?://)"
            + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" // ftp的user@
            + "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
            + "|" // 允许IP和DOMAIN（域名）
            + "([0-9a-z_!~*'()-]+\.)*" // 域名- www.
            + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名
            + "[a-z]{2,6})" // first level domain- .com or .museum
            + "(:[0-9]{1,4})?" // 端口- :80
            + "((/?)|" // a slash isn't required if there is no file name
            + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
        var re = new RegExp(strRegex);
        callback(re.test(str_url));
    };

    PKCms.prototype.arrayDropByItemKey = function (list_arr, drop_key, drop_value, callback) {
        if (typeof list_arr == "object") {
            for (var i = 0; i < list_arr.length; i++) {
                var tmp_item = list_arr[i];
                if (tmp_item.hasOwnProperty(drop_key) && (tmp_item[drop_key] == drop_value)) {
                    list_arr.splice(i, 1);
                }
            }
        }
        // console.log(list_arr);
        callback(list_arr);
    };

    /**
     * 计算百分比
     * @param   {number} num   分子
     * @param   {number} total 分母
     * @returns {number} 返回数百分比
     */
    PKCms.prototype.Percentage = function (num, total) {
        if (num == 0 || total == 0) {
            return 0;
        }
        return (Math.round(num / total * 10000) / 100.00);// 小数点后两位百分比
    };

    PKCms.prototype.nowDateTime = function () {
        var myDate = new Date();
        return myDate.getFullYear() + '-' + myDate.getMonth() + '-' + myDate.getDate() + ' '
            + myDate.getHours() + ':' + myDate.getMinutes();
    };

    PKCms.prototype.formatDateTime = function (value, format) {
        if (typeof format == "undefined") {
            format = "yyyy-MM-dd hh:mm:ss";
        }
        return value ? new Date(value * 1000).format(format) : "";
    }

    PKCms.prototype.useAppJs = function (app_name, fn) {
        if (typeof app_name == "string") {
            if (app_name == 'user') {
                loadingJS('/statics/layui/layui.js');
            }
            loadingJS('/statics/pkcms/app/' + app_name + '.js');
            var cls_name = 'PK' + app_name.slice(0,1).toUpperCase() +app_name.slice(1).toLowerCase();
            console.log(cls_name);
            var l_i = setInterval(function () {
                console.log(Object.getOwnPropertyNames(cls_name).length);
                if (Object.getOwnPropertyNames(cls_name).length > 0) {
                    clearInterval(l_i);
                    fn();
                }
            }, 1000);
        }
    }

    PKCms.prototype.useBDMapsJs = function (fn, APIKey) {
        if (APIKey === undefined) {
            let list_APIKey = ['Ikd2A16tuZY9jviM4wRNkO2Tu3DT5lwK', 'kTVcrmGo2kycDlhxdjtA3Mqe'];
            APIKey = list_APIKey[Math.ceil(Math.random() * list_APIKey.length)];
        }
        var script = document.createElement("script");
        script.src = "http://api.map.baidu.com/api?v=2.0&ak=" + APIKey + "&callback=initializeBaiDuMaps";
        document.body.appendChild(script);
        setTimeout(function () {
            fn();
        }, 500);
    }

    PKCms.prototype.JSONToUrlQuery = function (json) {
        return Object.keys(json).map(function (key) {
            // body...
            return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
        }).join("&");
    }

    /* 时间戳转化开始 */
    Date.prototype.format = function (fmt) { //author: meizz
        var o = {
            "M+": this.getMonth() + 1, //月份
            "d+": this.getDate(), //日
            "h+": this.getHours(), //小时
            "m+": this.getMinutes(), //分
            "s+": this.getSeconds(), //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //q是季度
            "S": this.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }

    win.PKCms = new PKCms();
}(window, document);